package register_config

import (
	"chain_bridge_service/internal/repository/mongodb/generate_address_config"
	"chain_bridge_service/internal/repository/mongodb/watch_address_config"
	"crypto/ecdsa"
	"crypto/sha256"
	"encoding/hex"
	"github.com/ethereum/go-ethereum/common/hexutil"
	"github.com/ethereum/go-ethereum/crypto"
	"github.com/mr-tron/base58"
	"go.mongodb.org/mongo-driver/mongo"
)

func NewModel() *RegisterConfig {
	return new(RegisterConfig)
}

func GenerateAddress(userId string, chainId uint, chainName string, client *mongo.Client, adminId string) error {

	var privateKeyHex string
	var address string
	switch chainName {
	case "TRX":
		privateKey, _ := crypto.GenerateKey()
		privateKeyBytes := crypto.FromECDSA(privateKey)
		publicKey := privateKey.Public()
		publicKeyECDSA, _ := publicKey.(*ecdsa.PublicKey)
		addrStr := crypto.PubkeyToAddress(*publicKeyECDSA).Hex()
		addrStr = "41" + addrStr[2:]
		addb, _ := hex.DecodeString(addrStr)
		firstHash := sha256.Sum256(addb)
		secondHash := sha256.Sum256(firstHash[:])
		secret := secondHash[:4]
		addb = append(addb, secret...)
		address = base58.Encode(addb)
		privateKeyHex = hexutil.Encode(privateKeyBytes)[2:]
	default:
		privateKeyRe, err := crypto.GenerateKey()
		if err != nil {
			return err
		}
		// 将私钥的D字段（其实是个大数）转换为字节切片
		privateKeyBytes := privateKeyRe.D.Bytes()

		// 将字节切片转换为十六进制字符串
		privateKeyHex = hex.EncodeToString(privateKeyBytes)
		address = crypto.PubkeyToAddress(privateKeyRe.PublicKey).Hex()
	}
	//这个域名到时候得换 这个到时候可以用127.0.0.1:8848
	callBack := "https://vip.skysp.info/api/v2/productUpgrade"

	//这里是存入u盾的address表 所以userId用系统用户的id取创建地址
	var watchAddressConfig watch_address_config.WatchAddressConfig
	watchAddressConfig.UserId = adminId
	watchAddressConfig.ChainId = chainId
	watchAddressConfig.PrivateKey = privateKeyHex
	watchAddressConfig.Address = address
	watchAddressConfig.ChainName = chainName
	watchAddressConfig.Type = "udun"
	watchAddressConfig.CallBackUrl = callBack
	err := watchAddressConfig.Create(client)
	if err != nil {
		return err
	}

	//这里是存入我们自己的address表
	var generateAddressConfig generate_address_config.GenerateAddressConfig
	generateAddressConfig.UserId = userId
	generateAddressConfig.ChainId = chainId
	generateAddressConfig.PrivateKey = privateKeyHex
	generateAddressConfig.Address = address
	generateAddressConfig.ChainName = chainName
	generateAddressConfig.Type = "udun"
	generateAddressConfig.CallBackUrl = callBack
	err = generateAddressConfig.Create(client)
	if err != nil {
		return err
	}
	return nil
}
